package com.example.lib_base.manager

import android.util.Log
import com.example.lib_base.model.Adv
import kotlin.random.Random

class AdvManager private constructor(){
    private val bmobManager = BmobManager.getInstance()
    var advs = emptyList<Adv>()
    private var preLoadIndex = -1

    companion object{
        private var instance:AdvManager? = null

        fun getInstance():AdvManager{
            if(instance == null) {
                synchronized(this) {
                    if(instance == null){
                        instance = AdvManager()
                    }
                }
            }

            return instance!!
        }
    }

    //获取所有图片的地址
    fun loadAdv(callback: (Boolean)->Unit){

            BmobManager.getInstance().queryAdv {
                it?.let { list ->
                    if (it.isNotEmpty()) {
                        advs = list
                        callback(true)
                    } else {
                        callback(false)
                    }
                }
            }
    }

    //随机获取一个图片
    fun getAdv():Adv?{
        if(advs.isEmpty()) return null
        if(preLoadIndex == -1) {
            preLoadIndex = Random.nextInt(advs.size)
        }
        return advs[preLoadIndex]

    }

}